package studio.raptor.databus.graph.exception;


import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理
 *
 * @author jack
 * @since 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {


  @ExceptionHandler(value = {NoHandlerFoundException.class})
  public ResponseEntity noHandlerFoundException(Exception ex) {

    return new ResponseEntity(ex.getMessage(), HttpStatus.NOT_FOUND);
  }

  @ExceptionHandler(value = Exception.class)
  public ResponseEntity defaultErrorHandler(Exception exception) throws Exception {
    return new ResponseEntity(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
  }

  @ExceptionHandler(value = {MethodArgumentNotValidException.class})
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public String handleArgumentNotValidException(MethodArgumentNotValidException e) {

    List<FieldError> errors = e.getBindingResult().getFieldErrors();
    StringBuilder sb = new StringBuilder();
    for (FieldError fe : errors) {
      sb.append(fe.getDefaultMessage() + "\n");
    }

    return sb.toString();
  }

}
